import itchat
import time
from itchat.content import TEXT


class WeChatSender:
    def __init__(self):
        """初始化 WeChat sender"""
        self.login_status = False
        # 登录回调函数
        itchat.auto_login(hotReload=True, loginCallback=self._on_login, exitCallback=self._on_logout)
        self.run_thread = itchat.run(blockThread=False)
        # 等待登录完成
        self._wait_for_login()

    def _on_login(self):
        """登录成功回调"""
        self.login_status = True
        print("微信登录成功")

    def _on_logout(self):
        """登出回调"""
        self.login_status = False
        print("微信已登出")

    def _wait_for_login(self, timeout=30):
        """等待登录完成"""
        start_time = time.time()
        while not self.login_status and (time.time() - start_time) < timeout:
            time.sleep(1)
        if not self.login_status:
            raise Exception("登录超时，请检查二维码扫描情况")

    def get_friend_list(self):
        """获取好友列表"""
        if not self.login_status:
            raise Exception("未登录，请先登录微信")
        return itchat.get_friends(update=True)

    def get_group_list(self):
        """获取群组列表"""
        if not self.login_status:
            raise Exception("未登录，请先登录微信")
        return itchat.get_chatrooms(update=True)

    def find_friend_by_name(self, name):
        """通过昵称查找好友"""
        friends = self.get_friend_list()
        for friend in friends:
            if friend['NickName'] == name:
                return friend
        return None

    def find_group_by_name(self, name):
        """通过群名查找群组"""
        groups = self.get_group_list()
        for group in groups:
            if group['NickName'] == name:
                return group
        return None

    def send_message_to_friend(self, friend_name, message):
        """向指定好友发送消息"""
        friend = self.find_friend_by_name(friend_name)
        if not friend:
            print(f"未找到好友：{friend_name}")
            return False

        try:
            itchat.send_msg(message, toUserName=friend['UserName'])
            print(f"已向 {friend_name} 发送消息：{message}")
            return True
        except Exception as e:
            print(f"发送消息给 {friend_name} 失败：{str(e)}")
            return False

    def send_message_to_group(self, group_name, message):
        """向指定群组发送消息"""
        group = self.find_group_by_name(group_name)
        if not group:
            print(f"未找到群组：{group_name}")
            return False

        try:
            itchat.send_msg(message, toUserName=group['UserName'])
            print(f"已向群组 {group_name} 发送消息：{message}")
            return True
        except Exception as e:
            print(f"发送消息到群组 {group_name} 失败：{str(e)}")
            return False

    def send_file_to_friend(self, friend_name, file_path):
        """向指定好友发送文件"""
        friend = self.find_friend_by_name(friend_name)
        if not friend:
            print(f"未找到好友：{friend_name}")
            return False

        try:
            itchat.send_file(file_path, toUserName=friend['UserName'])
            print(f"已向 {friend_name} 发送文件：{file_path}")
            return True
        except Exception as e:
            print(f"发送文件给 {friend_name} 失败：{str(e)}")
            return False

    def send_file_to_group(self, group_name, file_path):
        """向指定群组发送文件"""
        group = self.find_group_by_name(group_name)
        if not group:
            print(f"未找到群组：{group_name}")
            return False

        try:
            itchat.send_file(file_path, toUserName=group['UserName'])
            print(f"已向群组 {group_name} 发送文件：{file_path}")
            return True
        except Exception as e:
            print(f"发送文件到群组 {group_name} 失败：{str(e)}")
            return False

    def logout(self):
        """登出微信"""
        if self.login_status:
            itchat.logout()
            self.login_status = False
            print("已登出微信")


if __name__ == "__main__":
    try:
        # 初始化微信发送器
        wechat = WeChatSender()

        # 发送消息给好友
        wechat.send_message_to_friend("好友昵称", "这是一条来自Python脚本的测试消息")

        # 发送消息到群组
        wechat.send_message_to_group("群组名称", "这是一条发送到群组的测试消息")

        # 发送文件给好友（可选）
        # wechat.send_file_to_friend("好友昵称", "./test.txt")

        # 发送文件到群组（可选）
        # wechat.send_file_to_group("群组名称", "./test.txt")

        # 等待消息发送完成
        time.sleep(5)

        # 登出
        wechat.logout()
    except Exception as e:
        print(f"发生错误：{str(e)}")
